<template>
    <Layout>
        <Form ref="form1" :model="dataToQuery" :label-width="120">
            <Row v-show="!switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="单位名称：" prop="order">
                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName'
                                      :orgTree="true"
                                      :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="报告频次：">
                        <Select v-model='dataToQuery.reportingFrequency' clearable>
                            <Option v-for="item in dictMap['env-00031']" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8">
                    <!--<Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <!--<Button type="primary" class="ivu-btn-add" icon="md-cloud-download" :loading="buttonLoading" @click="batchDownload">批量下载</Button>-->
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
               :loading='pageStatus.loading'
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="this.getModalTitle('执行报告')" :transfer=false :mask-closable="false" v-model="dialogShow"
               v-if="dataToView && dialogShow" :width=800 class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                          :model="dataToView" :rules="mode === 'view'?{}:ruleCustom"
                          :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='所属二级集团：' prop='belongOrgId'>
                                    <div v-if="mode === 'view'">{{ dataToView.belongOrgName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写所属二级集团" type='text' v-model='dataToView.belongOrgId'></Input>-->
                                    <Select v-else class='query-form-el' placeholder="集团名称"
                                            v-model='dataToView.belongOrgId' label-in-value @on-change="belongChange">
                                        <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">
                                            {{item.orgName}}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='单位名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写单位名称" type='text' v-model='dataToView.companyId'></Input>-->
                                    <div v-else>
                                        <cascader-dom v-if="show" class='query-form-el' ref='orgCascader'
                                                      @setOrgInfo='setCompanyId' @setOrgname="setCompanyName"
                                                      :orgTree="true"
                                                      :currentOrgId="dataToView.companyId"
                                                      :rootOrgId="dataToView.belongOrgId"
                                                      :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='报告频次：' prop='reportingFrequency'>
                                    <div v-if="mode === 'view'">{{ dataToView.reportingFrequencyName }}</div>
                                    <Select v-else v-model='dataToView.reportingFrequency' clearable>
                                        <Option v-for="item in dictMap['env-00031']" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='上传人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写上传人" type='text' readonly
                                           v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around"
                             class="code-row-bg">
                            <Col span="23">
                                <FormItem v-if="mode === 'view'" label="执行报告：">
                                    <div v-show="dataToView.idFiles.length>0"
                                         v-for="(item,index) in dataToView.idFiles">
                                        <a @click="downloadFiles(item,index)"><span
                                                style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                        <Progress v-show="uploadListVisible[index]"
                                                  :percent="uploadListPercent[index]"></Progress>
                                    </div>
                                </FormItem>
                                <FormItem v-else label="执行报告：" prop="idFiles">
                                    <div>
                                        <Upload ref="upload"
                                                :before-upload="(file) => { beforeUpload1(file, 'id', 'executiveReport') }"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 10px">
                                                <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                                <!--<span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>-->
                                            </div>
                                        </Upload>
                                    </div>
                                    <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles"
                                         :key='item'>
                                        <a @click="downloadFiles(item,index)">{{ item.fileName }}</a>
                                        <Button type="text" icon="md-trash"
                                                @click="removeFile1(item.id, 'id', 'executiveReport')"
                                                style="margin-left: 5px;margin-bottom: 3px"/>
                                        <Progress v-show="uploadListVisible[index]"
                                                  :percent="uploadListPercent[index]"></Progress>
                                        <!--<Progress  v-show="filePercentVisible[index]" :percent="filePercent[index]"></Progress>-->
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='上传时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择上传时间" readonly
                                                v-model='dataToView.createDate'></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11"></Col>
                        </Row>

                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定
                </Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <div v-show="downloading"
             style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999;background-color:#000000;opacity:0.5;">
            <svg-bar style="position:absolute;top:50%;left:50%;margin-left:-100px;margin-top:-100px"
                     :options="options" :value="batchProcess"></svg-bar>
        </div>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    import svgBar from 'svg-progress-bar'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';

    export default {
        components: {
            cascaderDom,svgBar
        },
        data() {
            return {
                ...this.createCommonDataField(),
                imgUrl: "",
                columns1: [
                    {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    {key: 'belongOrgName', title: '所属二级集团', align: 'center', minWidth: 120,},
                    {key: 'companyName', title: '单位名称', align: 'center', minWidth: 120,},
                    {key: 'reportingFrequencyName', title: '报告频次', align: 'center', minWidth: 120,},
                    {key: 'createUserName', title: '上传人', align: 'center', minWidth: 120,},
                    {key: 'createDate', title: '上传时间', align: 'center', minWidth: 120, render: this.renderCellDate},
                    this.getActionColumns()
                ],
                ruleCustom: {
                    belongOrgId: [{required: true, message: '请填写所属二级集团', trigger: 'change',}],
                    companyId: [{required: true, message: '请填写单位名称', trigger: 'change',}],
                    reportingFrequency: [{required: true, message: '请填写报告频次', trigger: 'change',}],
                    createUserName: [{required: true, message: '请填写上传人', trigger: 'change',}],
                    createDate: [{required: true, message: '请填写上传时间', trigger: 'change', type: 'date'}],
                    idFiles: [{
                        validator: (rule, value, callback) => {
                            if (this.dataToView.idFiles.length < 1) {
                                callback('附件必须上传')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }]
                },
                tableHeight: 10,
                dictMap: {},
                punishment: false,
                penaltyAmount: true,
                // api
                queryUrl: Api.queryEnTable.replace('{{table}}', 'ExecutiveReport'),
                exportUrl: Api.exportEnTable.replace('{{table}}', 'ExecutiveReport'),
                deleteUrl: Api.deleteEnTable.replace('{{table}}', 'ExecutiveReport'),
                getUrl: Api.getEnTable.replace('{{table}}', 'ExecutiveReport'),
                updateUrl: Api.updateEnTable.replace('{{table}}', 'ExecutiveReport'),
                saveUrl: Api.saveEnTable.replace('{{table}}', 'ExecutiveReport'),

                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                show: true,
                buttonLoading: false,
                batchProcess:0,
                downloading:false,
            }
        },
        computed: {
            options: function() {
                return {
                    radius: 50,//大小
                    duration: 2,//变化时间长度
                    circleWidth: 5,//圆环宽度
                    pathColors: ['#A2A2A2', '#FA5657'], //圆环 底色和 上面的颜色
                    circleLineCap: 'round',//进度条 形状  圆环 或者矩形
                    text: function (value) {
                        return this.htmlifyNumber(value) + '<span style="font-size: 0.4em;">%</span>';
                    },
                    textColor: 'rgb(33, 150, 243)'
                }
            }
        },
        async mounted() {
            this.setTableHeight();
            await this.$http.get(Api.queryDictBycode+"env-00031",{}).then((res)=>{
                // 数据字典 list 转 map，方便调用
                this.dictMap = {
                    'env-00031':this.dictListToMap(res.data.data['env-00031']),
                }
            })
            this.query();
            this.selectSecGroupNames()
            this.$Loading.config({
                color: '#5cb85c',
                failedColor: 'red',
                height: 5
            });
        },
        methods: {
            ...pageCommonFunction,
            batchDownload(){
                var _this = this;
                _this.downloading = true
                var url = Api.mongoBatchDownload;
                var ids = [];
                var fileNames = [];
                _this.dataTable.forEach(item=>{
                    ids.push(item.id)
                    fileNames.push(item.companyName+'-'+item.name)
                })
                let formData = new FormData();
                formData.append("ids", ids); // 文件对象
                formData.append("fileNames", fileNames); // 文件对象
                _this.$http.post(url, formData, {
                    responseType: 'blob',      //告诉服务器我们需要的响应格式
                    progress:function(e){
                        _this.batchProcess = 100 * (e.loaded / e.total);
                        if(_this.batchProcess == 100){
                            _this.downloading = false;
                        }
                    }
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: 'application/zip'     //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = _this.formatDate(new Date(), 'yyyyMMddhhmmss') + ".zip";
                    aLink.click()
                    document.body.appendChild(aLink)
                }, function(res){
                    _this.$Loading.error();
                })
            },

            selectSecGroupNames() {
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevel = res.data.data
                }).catch(e => {
                })
            },
            belongChange(value) {
                this.$set(this.dataToView, 'belongOrgId', value.value)
                this.$set(this.dataToView, 'belongOrgName', value.label)
                this.dataToView.companyId = null
                this.dataToView.companyName = null
                this.$refs.orgCascader.resetCurrentOrg();
                this.show = false;
                setTimeout(() => {
                    this.show = true
                }, 0)
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {
                this.queryAjax();
            },

            submit(name) {
                this.submitAjaxValidateField(name);
            },
            createEmptyDataToAdd() {
                return {
                    createDate: new Date(),
                    createUserId: this.currentUser.userId,
                    createUserName: this.currentUser.userName,
                    id: this.get_uuid(),
                    idFiles: [],
                }
            },
            async afterDataToViewInit() {
                await this.getFiles1('id', 'executiveReport');
            },

        },
        watch: {},
    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }

</style>